package main

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"regexp"
	"strings"
	"sync"
)

var (
	pic_re  = regexp.MustCompile(`<img src="(.*?)"/>`)
	saveDir = ""
)

var pic sync.WaitGroup

type SiteMap struct {
	Url []Url `xml:"url"`
}

type Url struct {
	Loc string `xml:"loc"`

	Lastmod string `xml:"lastmod"`

	Priority string `xml:"priority"`
}

func main() {
	// 创建存放目录
	path, _ := os.Getwd()
	saveDir = path + "/loft"

	_, dirErr := os.Stat(saveDir)
	if os.IsNotExist(dirErr) {
		os.Mkdir(saveDir, os.ModeDir)
	}

	content := httpGet("http://sexy.faceks.com/sitemap.xml")
	var siteXml SiteMap
	err := xml.Unmarshal(content, &siteXml)
	if err != nil {
		log.Fatal(err)
	}
	for _, v := range siteXml.Url {
		go getPic(v.Loc)
		fmt.Println(v.Loc)
		pic.Add(1)
	}
	pic.Wait()

}

func httpGet(url string) []byte {
	resp, err := http.Get(url)
	if err != nil {
		return nil
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil
	}
	return body
}

func getName(url string) string {
	index := strings.LastIndex(url, "/")
	if index < 0 {
		return url
	}
	return url[index+1:]
}

func getPic(url string) {
	d := httpGet(url)
	if d == nil {
		return
	}

	picSavePath := saveDir
	_, erro := os.Stat(picSavePath)
	if os.IsNotExist(erro) {
		os.Mkdir(picSavePath, os.ModeDir)
	}

	urls := pic_re.FindAllStringSubmatch(string(d), 100)
	for _, value := range urls {
		picSaveName := picSavePath + "/" + getName(value[1])
		f, e := os.Create(picSaveName)
		if e == nil {
			f.Write(httpGet(value[1]))
		}
		defer f.Close()
	}
	pic.Done()
}
